package turtle.system.invest.evaluate;

import java.io.PrintWriter;
import java.text.DecimalFormat;
import java.util.ArrayList;

import org.osite.util.ToolKit;
import org.osite.xml.XmlConstructor;
import org.osite.xml.XmlParam;

import turtle.system.invest.Environment;
import turtle.system.invest.IndexSeries;
import turtle.system.invest.rule.AbstractRule;
import turtle.system.invest.rule.InvestHistory;
import turtle.system.invest.rule.InvestRunnable;

public class PrintProfit implements InvestRunnable {
	
	private static final String STDOUT_STR = "<stdout>";
	private static final DecimalFormat RATIO_FORMAT = new DecimalFormat("0.000");
	private String output;
	
	@XmlConstructor
	public PrintProfit(
			@XmlParam(value = "output", preset = STDOUT_STR) String output) {
		this.output = output;
	}
	
	private static String toCsvString(String ... array) {
		StringBuilder sb = new StringBuilder();
		if (array.length > 0) sb.append(array[0]);
		for (int i = 1, n = array.length; i < n; ++i)
			sb.append(", ").append(array[i]);
		return sb.toString();
	}

    @Override
    public void run(Environment environment) {
        InvestHistory history = environment.getInvestHistory();
        
        IndexSeries series = environment.get(Environment.WTX1 + ".close");
        int end = environment.get(Simulate.END_TIMESTAMP);
        long profit = history.getProfit(series.getValue(end - 1));
        
        AbstractRule rule = environment.get(AbstractRule.KEY_RULE);
        
        ArrayList<String> output = ToolKit.newArrayList();
        
        output.add(rule.toString());
        output.add(Long.toString(profit));
        output.add(Long.toString(rule.getMaxGain()));
        output.add(Long.toString(rule.getMaxLoss()));
        output.add(RATIO_FORMAT.format((double) rule.getMaxGain() / rule.getMaxLoss()));
        output.add(Long.toString(rule.getHighLevel()));
        output.add(Long.toString(rule.getLowLevel()));
        
        if (STDOUT_STR.equals(this.output)) {
        	System.out.println(toCsvString(output.toArray(new String[0])));
        } else {
            PrintWriter writer = environment.get(this.output);
        	writer.println(toCsvString(output.toArray(new String[0])));
        }
    }
}
